#pragma once
#include "../log/ckflog.hpp"
#include <chrono>

namespace ckflogs
{
    class LogTester
    {
        /*
        function:
            使用日志器名称logger_name
            打印日志总条数：msg_cnt
            单条日志长度：msg_len
            并发使用该日志器的线程数量：thr_cnt
        result:
            输出所有日志消息的总耗时
            单位时间内（每秒），日志器Logger能输出的日志消息条数(=总条数/总耗时)，输出日志消息多少MB(=总条数*单条长度/总耗时)
        */
    public:
        static void test(const std::string &logger_name, size_t msg_cnt, size_t msg_len, size_t thr_cnt)
        {
            using namespace std::chrono;
            // 0.获取日志器logger
            Logger::Ptr logger = getLogger(logger_name);
            if (logger == nullptr)
            {
                DF_DEBUG("logger:%s not found", logger_name.c_str());
                return;
            }

            std::string msg_str('1', msg_len);

            // 1.创建线程, 并在不同线程中调用logger
            std::vector<std::thread> threads;
            std::vector<duration<double>> time_spans(thr_cnt);
            size_t msg_thr_cnt = msg_cnt / thr_cnt; // 每个线程所输出的日志条数

            for (size_t i = 0; i < thr_cnt; i++)
            {
                threads.emplace_back([&, i]
                                     {
                    high_resolution_clock::time_point begin = high_resolution_clock::now();
                    for(int j = 0; j < msg_thr_cnt; j++)
                        logger->debug("%s",msg_str.c_str());
                    high_resolution_clock::time_point end = high_resolution_clock::now();

                   time_spans[i] = duration_cast<duration<double>>(end-begin); });
            }

            for (auto &thr : threads)
            {
                thr.join();
            }

            double max_span = time_spans[0].count();
            for (auto &time_span : time_spans)
            {
                max_span = std::max(max_span, time_span.count());
            }

            size_t msg_per_cnt = msg_cnt / max_span;
            size_t msg_per_size = (msg_cnt * msg_len) / (max_span * 1024); // byte->MB

            std::cout << "日志器: " << logger_name << " "
                      << "线程数量: " << thr_cnt << std::endl;
            std::cout << "\t 打印日志总条数: " << msg_cnt << "\t 总耗时: " << max_span << "s" << std::endl;
            std::cout << "\t 单位时间输出日志条数: " << msg_per_cnt << "条" << std::endl;
            std::cout << "\t 单位时间输出日志大小: " << msg_per_size << "MB" << std::endl;
        }
    };
}
